/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ipo.mm.web.actions;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.export.JExcelApiExporter;
import net.sf.jasperreports.engine.export.JExcelApiExporterParameter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRRtfExporter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;
import org.ipo.mm.ejb.entities.User;
import org.ipo.mm.web.formbeans.ReportsBean;
import org.ipo.mm.web.util.BreadCrumbs;
import org.ipo.mm.web.util.ConstantManager;
import org.ipo.mm.web.util.ReportsNameFileMappings;

/**
 *
 * @author predrag
 */
public class ReportMenuAction extends org.apache.struts.action.Action {

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        ActionForward actionForward = null;

        if (isCancelled(request)) {
            actionForward = executeCancel(mapping, form, request, response);
        } else {

            User currentUser = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);
            MessageResources mResources = getResources(request);
            ReportsBean reportsBean = (ReportsBean) form;
            ReportsNameFileMappings mapps = new ReportsNameFileMappings();
            String fileName= mapps.getFileForReport(reportsBean.getReportName());
            //PrintWriter out = response.getWriter();
            ServletOutputStream servletOutputStream = response.getOutputStream();
            InputStream reportStream = getServlet().getServletConfig().getServletContext().getResourceAsStream("/WEB-INF/reports/"+fileName);

            try{
              if(reportStream==null){
                  response.setContentType("text/html;charset=UTF-8");
                  // TODO output your page here

                  servletOutputStream.println("<html>");
                  servletOutputStream.println("<head>");
                  servletOutputStream.println("<title>Report info</title>");
                  servletOutputStream.println("</head>");
                  servletOutputStream.println("<body>");
                  servletOutputStream.println("<h2>Report is not implemented jet!<br/>Izveštaj još nije implementiran</h2>");
                  servletOutputStream.println("</body>");
                  servletOutputStream.println("</html>");
                  servletOutputStream.close();
                  return actionForward;
              }
              else{
                  if(reportStream.available()>0) {
                    //Logger.getLogger(getClass().getName()).log(Level.INFO, "našo report");
                   }
                   else{
                                   
                      try {
                            // TODO output your page here
                            servletOutputStream.println("<html>");
                            servletOutputStream.println("<head>");
                            servletOutputStream.println("<title>Report info</title>");
                            servletOutputStream.println("</head>");
                            servletOutputStream.println("<body>");
                            servletOutputStream.println("<br/><h2>Report is not implemented jet!!<br/>Izveštaj još nije implementiran</h2>");
                            servletOutputStream.println("</body>");
                            servletOutputStream.println("</html>");
                      } finally {
                          servletOutputStream.close();
                          return actionForward;
                      }
                   }
                }
                Class.forName("com.mysql.jdbc.Driver");
               String connStr =  getServlet().getServletContext().getInitParameter("connectionString");
               Connection connection = DriverManager.getConnection(connStr);
               Logger.getLogger(getClass().getName()).log(Level.INFO, "prije JasperRunManager ");
               HashMap parameterMap = new HashMap();
               parameterMap.put("idsInArray", reportsBean.getIdsInArray());

               //JasperPrint jasperPrint = JasperFillManager.fillReport(reportStream, parameterMap,connection);

 /*
               JRXlsExporter exporter = new JRXlsExporter();
                    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
                    exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, getServlet().getServletConfig().getServletContext().getRealPath("/")+"test.xls");
                    exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,
                            Boolean.FALSE);
                    exporter.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE,
                            Boolean.TRUE);
                    exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND,
                            Boolean.FALSE);
                    exporter.setParameter(JRXlsExporterParameter.IS_IGNORE_GRAPHICS,
                            Boolean.FALSE);
                    exporter.setParameter(JRExporterParameter.OFFSET_X,new Integer(0));
                    exporter.setParameter(JRExporterParameter.OFFSET_Y,new Integer(0));

                exporter.setParameter(JRXlsExporterParameter.OUTPUT_STREAM,servletOutputStream);
                response.setHeader("Content-Disposition", "inline;filename=" + fileName+".xls");
                response.setContentType("application/vnd.ms-excel");

                    exporter.exportReport();
*/
  
/*
                    JRPdfExporter pdfExporter = new JRPdfExporter();
                    pdfExporter.setParameter(JRExporterParameter.JASPER_PRINT,jasperPrint);
                    pdfExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,getServlet().getServletConfig().getServletContext().getRealPath("/")+"test.pdf");
                    pdfExporter.exportReport();
*/


               /*
                 JExcelApiExporter jExcelApiExporter = new JExcelApiExporter();
               jExcelApiExporter.setParameter(JRExporterParameter.JASPER_PRINT,jasperPrint);
               jExcelApiExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, getServlet().getServletConfig().getServletContext().getRealPath("/")+"test.xls");
               jExcelApiExporter.setParameter(JExcelApiExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
jExcelApiExporter.setParameter(JExcelApiExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
jExcelApiExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
//jExcelApiExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, os);
jExcelApiExporter.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
jExcelApiExporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
jExcelApiExporter.setParameter(JRXlsExporterParameter.CHARACTER_ENCODING,"utf-8");
jExcelApiExporter.setParameter(JExcelApiExporterParameter.MAXIMUM_ROWS_PER_SHEET, 50000);
jExcelApiExporter.setParameter(JExcelApiExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE);
jExcelApiExporter.setParameter(JExcelApiExporterParameter.SHEET_NAMES, new String[]{"Employees"});
jExcelApiExporter.exportReport();
*/


              response.setContentType("application/pdf");
              response.addHeader("Content-Disposition","attachment; filename="+reportsBean.getReportName()+".pdf");
              JasperRunManager.runReportToPdfStream(reportStream,servletOutputStream, parameterMap, connection);


/*RTF
                    try{
                        JRRtfExporter rtfExporter = new JRRtfExporter();
                        rtfExporter.setParameter(JRExporterParameter.JASPER_PRINT,jasperPrint);
                        rtfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM,servletOutputStream);
                        response.setHeader("Content-Disposition", "inline;filename=" + fileName+".rtf");
                        //response.setContentType("text/rtf");
                        response.setContentType("application/msword");
                        rtfExporter.exportReport();
                    }
                    catch (JRException e)
                    {
                        Logger.getLogger(getClass().getName()).log(Level.INFO, e.toString());
                    }
*/
               servletOutputStream.flush();
               servletOutputStream.close();
               //Logger.getLogger(getClass().getName()).log(Level.INFO, "flush close");

           } catch(Exception e) {
               //reportStream.close();
               Logger.getLogger(getClass().getName()).log(Level.INFO, "Exception{0}", e.toString());

               response.setContentType("text/html;charset=UTF-8");
             
               try {
                   // TODO output your page here
                   servletOutputStream.println("<html>");
                   servletOutputStream.println("<head>");
                   servletOutputStream.println("<title>Report info</title>");
                   servletOutputStream.println("</head>");
                   servletOutputStream.println("<body>");
                   servletOutputStream.println("<h1>"+e.toString()+"</h1>");
                   servletOutputStream.println("</body>");
                   servletOutputStream.println("</html>");
                  } finally {
                      servletOutputStream.close();
                      return null;
                  }

           }
            finally
            {
                  reportStream.close();
            }


            String submit = reportsBean.getSubmit();
            actionForward = executeCreate(mapping, form, request, response, reportsBean, currentUser);
           

        }

        return actionForward;
    }



    private ActionForward executeCreate(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response, ReportsBean reportsBean, User user) throws Exception {


        ActionForward actionForward;
        actionForward = mapping.getInputForward();        

        return actionForward;
    }

    private ActionForward executeCancel(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);
        bc.pop();
        ActionForward actionForward = bc.pop().getActionForward();
        return actionForward;
    }
 
}
